<template>
  <div class="login-box">
    <el-card class="form-box">
      <div slot="header" class="clearfix">
        <span>黑马面经后台</span>
      </div>
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item label="用户名:" label-width="80px" prop="username">
          <el-input
            placeholder="输入用户名"
            v-model="form.username"
            @keyup.enter.native="fn(form.username)"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" label-width="80px" prop="password">
          <el-input
            ref="qh"
            placeholder="输入用户密码"
            type="password"
            v-model="form.password"
            @keyup.enter.native="login"
          ></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login" :loading="flag"
            >登录</el-button
          >
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/utils/user'
export default {
  name: 'login-page',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 11, message: '用户名长度为5-11位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^[a-z,A-Z,0-9]{5,11}$/,
            message: '密码长度为5-11位',
            trigger: 'blur'
          }
        ]
      },
      flag: false
    }
  },
  methods: {
    async login() {
      try {
        await this.$refs.form.validate()
        this.flag = true
        const res = await login(this.form)
        this.$store.commit('user/setToken', res.data.token)
        this.flag = false
        this.$message.success('登录成功')
        this.$router.push('/')
        console.log('发起ajxos请求' + res)
      } catch (err) {
        console.log(err)
        if (err.response && err.response.status === 400) {
          this.$message.error(err.response.data.message)
        } else {
          this.$message.error('出错了')
        }
        this.flag = false
      }
    },
    reset() {
      this.$refs.form.resetFields()
    },
    fn(value) {
      if (value) {
        this.$refs.qh.focus()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.login-box {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/login-bg.svg') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .form-box {
    width: 420px;
    // height: 370px;
    // background-color: pink;
  }
  ::v-deep .el-card__header {
    color: #fff;
    text-align: center;
    background-color: #727cf5;
  }
  .btns {
    text-align: center;
  }
}
</style>
